//
//  ChangeCityViewController.m
//  shise
//
//  Created by Darling❤️ on 14/12/17.
//  Copyright (c) 2014年 Darling❤️. All rights reserved.
//

#import "ChangeCityViewController.h"
#import "NetHandler.h"
#import "City.h"
#import "ProvinceViewController.h"
#import "CityViewController.h"

@interface ChangeCityViewController ()

@property(nonatomic, retain)UIAlertView *alertView;

@end

@implementation ChangeCityViewController
- (void)dealloc
{
    [_arr release];
    [_tableView release];
    [_city release];
    [_alertView release];
    [super dealloc];
}
//初始化方法
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self handelData];
    }
    return self;
}

//处理数据
- (void)handelData
{
    
    NSString *str = @"https://api.shiseapp.com/v2/user/profile/location/?_city=%E9%A6%99%E6%B8%AF&_device=Matcha%20v2.5.0%20%28iPhone%206,%208.1.1%29&_version=2.5.0&conf_ver=1418876027&gps=38.884307,121.541181&type=localcity&uuid=b611c1feab43d2ee1585a574f539263f";
    //解析数据
    [NetHandler getDataWithUrl:str completion:^(NSData *data) {
        NSError *error = nil;
        NSMutableDictionary *tempDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error: &error];
 
    //定义一个数组，存储解析后的数据
        NSArray *cityArr = [tempDic objectForKey:@"data"];
        //初始化这个数组
        self.arr = [NSMutableArray array];
        //遍历数组（存在字典中）
        for (NSMutableDictionary *dic in cityArr) {
            //定义个对象，把得到的值给对象赋值
            City *city = [[City alloc]initWithDictionary:dic];
            //把对象付给数组
            [self.arr addObject:city];
            [city release];
        }
//        City *city1 = [self.arr objectAtIndex:3];
//        NSLog(@"%@",city1.title);
        //刷新数据
        [self.tableView reloadData];
    }];
    

    
}




- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"选择城市";
    self.view.backgroundColor = [UIColor whiteColor];
    //选择城市的tableView设置
    self.tableView = [[UITableView alloc]initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
    self.tableView.rowHeight = 50;
    self.tableView.sectionHeaderHeight = 40;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    [_tableView release];
    
}

//两个协议方法

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *str = @"reuse";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:str]autorelease];
    }
    City *city = [self.arr objectAtIndex:indexPath.row];
    cell.textLabel.text = city.title;
//    NSLog(@"%@", city.title);
    
    return cell;
}




// 点击cell推出下一个详细页面 该省下得所有市
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    // 从数组中取出城市对象 该对象有一个属性是这个省的名字
    City *city = [self.arr objectAtIndex:indexPath.row];
    // 定义市视图控制器的实力对象
    CityViewController *cityVC = [[CityViewController alloc] init];

    // 定义一个可变数组 用来装该省下得所有的市
    NSMutableArray *tempArray = [NSMutableArray array];
    // 点击某个省推出的市视图控制器用的链接地址
    NSString *string = [NSString stringWithFormat:@"https://api.shiseapp.com/v2/user/profile/location/?_version=2.5.0&conf_ver=1419417114&gps=38.883064,121.539805&sheng=%@&type=localcity&uuid=b611c1feab43d2ee1585a574f539263f", city.title];
//    NSLog(@"数组地址%@", string);
    
    [NetHandler getDataWithUrl:string completion:^(NSData *data) {
        
        NSError *error = nil;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
        NSArray *arr = [dic objectForKey:@"data"];
        // 数组中的每一个元素是一个字典 字典中又一个key对应的value是市的名字 要把每一个字典中的市的名字取出撞到刚才定义好的数组中
        for (NSDictionary *tempDic in arr) {
            
            // 首先判断字典tempDic中key为selectData的value是否为空 如果是空就不能加入到数组中因为数组中的元素不能为空
            NSString *value = [tempDic objectForKey:@"selectData"];
            if (value.length > 0 && indexPath.row != 0) {
                
                // 如果有元素就往数组里面加
                // 开始往可变数组中添加“市”元素
                [tempArray addObject:[tempDic objectForKey:@"selectData"]];
                
            }
        }
        
        // 进行判断如果数组中有元素且元素个数大于1个代表该省是有市的
        if (tempArray.count > 1) {
            
            cityVC.province = city.title;
            
            [self.navigationController pushViewController:cityVC animated:YES];
            
            
        } else if(tempArray.count == 1 ) {
            
            NSString *ss = [tempArray objectAtIndex:0];
            
            [[NSNotificationCenter defaultCenter]postNotificationName:@"changeProvince" object:ss userInfo:nil];
            self.alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"更改成功" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
            [self.alertView show];
            [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(performDismiss:) userInfo:nil repeats:NO];
            
        }
    }];
    [cityVC release];
    
}



- (void)performDismiss:(NSTimer *)timer
{
    [self.alertView dismissWithClickedButtonIndex:0 animated:YES];
    [self.alertView release];
    self.alertView = nil;
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
